import React from "react"

import "@/components/common/RScrollbar/RScrollbar.component.styl"

class RScrollbar extends React.Component {
    constructor(props) {
        super(props);
        this.scrollToBottomCallback = this.scrollToBottomCallback.bind(this);
        this.whileScrollingThrottle = this.whileScrollingThrottle.bind(this);
        this.onScrollCallback = this.onScrollCallback.bind(this)
    }

    componentDidMount() {
        this.init();
    }

    componentWillUnmount() {
        this.whileScrollingThrottle().cancel();
    }

    init() {
        let {axis} = this.props;

        $(".r-scrollbar").mCustomScrollbar({
            axis: axis ? axis : "y",
            advanced: {
                updateOnContentResize: true
            },
            mouseWheel: {
                deltaFactor: 50
            },
            theme: "minimal",
            scrollInertia: 200,
            scrollbarPosition: "outside",
            callbacks: {
                onTotalScroll: this.scrollToBottomCallback,
                whileScrolling: _.throttle(this.whileScrollingThrottle, 200),
                onScroll: this.onScrollCallback
            }
        })
    }

    /**
     * 一次滚动事件结束回调
     */
    onScrollCallback() {
        this.props.onScroll && this.props.onScroll();
    }

    /**
     * 滚动时回调
     */
    whileScrollingThrottle() {
        this.props.whileScrolling && this.props.whileScrolling(this);
    }

    /**
     * 滚动到底部回调
     */
    scrollToBottomCallback() {
        this.props.scrollToBottom && this.props.scrollToBottom();
    }

    /**
     * 滚动到某个位置
     * @param position
     */
    scrollTo(position) {
        $(".r-scrollbar").mCustomScrollbar("scrollTo", position, {scrollEasing: "easeOut"})
    }

    update() {
        $(".r-scrollbar").mCustomScrollbar("update")
    }

    disable() {
        $(".r-scrollbar").mCustomScrollbar("disable")
    }

    render() {
        return (
            <div className="r-scrollbar">
                {_.map(this.props.children, item => item)}
            </div>
        )
    }
}

export default RScrollbar
